<template>
  <div class="comment-user-avatar">
    <div>
      <el-avatar
        :class="userFormInfo.user.avatar ? '' : 'gray'"
        :src="
          userFormInfo.user.avatar ? userFormInfo.user.avatar : offLineProfile
        "
      >
        <template #default>
          <div class="image-slot">
            <el-image
              :src="randomArrayIndex(store.state.defaultErrorImageUrl)"
              fit="cover"
            ></el-image>
          </div>
        </template>
      </el-avatar>
      <i class="fa fa-qq" aria-hidden="true"></i>
    </div>
  </div>
  <div class="user-comment-Info">
    <el-form :model="userFormInfo" :rules="rules" ref="formRef">
      <el-form-item label="QQ">
        <el-input
          placeholder="将自动拉取昵称和头像"
          @blur="getQQInfo"
          clearable
          v-model="userFormInfo.user.name"
        ></el-input>
      </el-form-item>
      <el-form-item prop="user.email" label="Email">
        <el-input
          placeholder="邮箱 (必须* )"
          clearable
          v-model="userFormInfo.user.email"
        ></el-input>
      </el-form-item>
      <el-form-item label="个人网站">
        <el-input
          placeholder="网站地址"
          clearable
          v-model="userFormInfo.user.website"
        >
          <template #prepend>Http://</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="submit-comment">
      <el-button type="success" round @click="submitForm(formRef)"
        >提交评论</el-button
      >
      <el-button type="danger" round @click="resetForm(formRef)"
        >取消评论</el-button
      >
    </div>
  </div>
</template>

<script setup>
  import { getApikey } from '@/api/thirdParty/thirdparty'
  import { getQQInfos } from '@/api/user/user'
  import { inject, reactive, ref } from 'vue'
  import { randomArrayIndex } from '@/utils/randomArrayElemt'
  import { useStore } from 'vuex'
  import { validateComment, validateEmail } from '@/utils/validate'
  import { repComment } from '@/api/article/article'
  import offLineProfile from '@/assets/images/offLine.jpg'

  const props = defineProps({
    commentsData: {
      type: Object
    }
  })

  const emits = defineEmits(['PidReply'])

  const store = new useStore()

  //评论用户信息
  const userFormInfo = reactive({
    blogId: null,
    parentId: -1,
    context: '',
    lastAccount: '',
    user: {
      email: '',
      name: '',
      avatar: '',
      website: ''
    }
  })

  //表单Ref
  const formRef = ref()

  //刷新评论方法
  const refreshComments = inject('refreshComments')

  // 表单验证规则
  const rules = reactive({
    comment: [
      {
        required: true,
        message: '评论不能为空',
        trigger: 'blur'
      },
      {
        min: 1,
        trigger: 'blur'
      },
      {
        validator: validateComment,
        trigger: 'blur'
      }
    ],
    'user.email': [
      {
        required: true,
        message: '邮箱不能为空'
      },
      {
        validator: validateEmail,
        trigger: 'blur'
      }
    ]
  })

  /**
   * 获取qq信息
   * @param event
   */
  const getQQInfo = () => {
    if (
      userFormInfo.lastAccount === userFormInfo.user.name.trim() ||
      userFormInfo.user.name.trim() === '' ||
      isNaN(parseInt(userFormInfo.user.name))
    ) {
      return
    }
    getQQInfos({
      qqNumber: userFormInfo.user.name.trim()
    })
      .then((res) => {
        userFormInfo.user.name = res.data.name ? res.data.name : ' '
        userFormInfo.user.email = res.data.email
        userFormInfo.user.avatar = res.data.avatar
      })
      .catch(() => {
        return ElMessage.error('网络开小差了~~~~')
      })
    // 记录上次提交的信息,防止重复请求
    userFormInfo.lastAccount = userFormInfo.user.name.trim()
  }

  const submitForm = (formEl) => {
    //从父元素传递过来的评论
    userFormInfo.context = props.commentsData.commentsForm.comment
    if (userFormInfo.context.trim().length === 0) {
      return ElMessage({
        showClose: true,
        message: '评论不能为空哦',
        type: 'error',
        offset: 100
      })
    }
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        // 判断评论是父评论还是子评论
        if (props.commentsData.item) {
          userFormInfo.parentId = props.commentsData.item.id
          userFormInfo.blogId = props.commentsData.item.blogId
        } else {
          userFormInfo.parentId = props.commentsData.subItem.id
          userFormInfo.blogId = props.commentsData.subItem.blogId
        }

        const { data } = await getApikey()
        const address = data.IP_Address
        await repComment({
          blogId: userFormInfo.blogId,
          parentId: userFormInfo.parentId,
          context: userFormInfo.context,
          address: address,
          user: {
            email: userFormInfo.user.email,
            name: userFormInfo.user.name,
            avatar: userFormInfo.user.avatar,
            html_url: userFormInfo.user.website
          }
        })
          .then((res) => {
            if (res.code === 200) {
              props.commentsData.commentsForm.comment = ''
              // 关闭评论框
              emits('PidReply')
              // getCommentsDetails(userFormInfo.blogId)
              refreshComments()
              return ElMessage({
                showClose: true,
                message: '评论成功',
                type: 'success',
                offset: 100
              })
            }
            return ElMessage.error('评论失败')
          })
          .catch(() => {
            return ElMessage.error('评论超时')
          })
      } else {
        console.log('error submit!')
        return false
      }
    })
  }

  const resetForm = (formEl) => {
    //关闭评论窗口
    emits('PidReply')
    if (!formEl) return

    formEl.resetFields()
  }
</script>

<style lang="less" scoped>
  .comment-user-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 10px;

    i {
      position: relative;
      right: 15px;
      bottom: 3px;
      color: #3cb45e;
      border-radius: 40%;
    }
  }

  .user-comment-Info form {
    display: flex;
    justify-content: space-around;
  }

  @media (max-width: 860px) {
    .comment-box .el-avatar {
      display: block !important;
    }

    .comment-user-avatar {
      padding-bottom: 0;

      div {
        //margin: 0;
        height: 20px;
      }

      i {
        right: -25px;
        bottom: 20px;
      }
    }

    .user-comment-Info form {
      flex-direction: column;

      .el-form-item {
        display: block;
      }
    }
  }

  .submit-comment {
    display: flex;
    justify-content: center;

    button {
      margin: 10px 30px;
    }
  }
</style>
